package com.dongnam.quanly.web.danhmuc.taikhoannganhang;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.CellFormat;
import jxl.format.Orientation;
import jxl.format.ScriptStyle;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.Number;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.TaiKhoanNganHangController;
import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.common.model.KhoHang;
import com.dongnam.quanly.common.model.NganHang;
import com.dongnam.quanly.common.model.TaiKhoanNganHang;
import com.dongnam.quanly.common.model.enumtype.LoaiTaiKhoanNganHang;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.util.CsvUtil;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "TaiKhoanNganHangBean")
@SessionScoped
public class TaiKhoanNganHangBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(TaiKhoanNganHangBean.class);
	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;
	private TaiKhoanNganHangModel tknganhangModel;

	// for add TaiKhoanNganHang
	private TaiKhoanNganHang tknganhang;
	private boolean isEdit = false;
	private boolean taiKhoaiDoiTac = true;
	// for download file
	private StreamedContent file;

	// for load danh sach TaiKhoanNganHang
	private TaiKhoanNganHangController tknganhangController;

	// for edit TaiKhoanNganHang
	private TaiKhoanNganHang selectedtknganhang;

	public TaiKhoanNganHangBean() {
		super();
		tknganhang = new TaiKhoanNganHang();
		loadtknganhang();
		// TODO Auto-generated constructor stub
	}

	public TaiKhoanNganHangController getTknganhangController() {
		if (tknganhangController == null)
			tknganhangController = new TaiKhoanNganHangController();
		return tknganhangController;
	}

	public void setTknganhangController(TaiKhoanNganHangController tknganhangController) {
		this.tknganhangController = tknganhangController;
	}

	public void downloadFileCSV() {

		File excelfile = new File("TAI_KHOAN_NGAN_HANG.xls");
		List<TaiKhoanNganHang> list = getTknganhangController().findAll();
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(6, 30);

			sheet.addCell(new Label(0, 0, "Số tài khoản", titleformat));
			sheet.addCell(new Label(1, 0, "Ngân hàng", titleformat));
			sheet.addCell(new Label(2, 0, "Chi nhánh", titleformat));
			sheet.addCell(new Label(3, 0, "Địa chỉ nơi mở", titleformat));
			sheet.addCell(new Label(4, 0, "Ghi chú", titleformat));
			sheet.addCell(new Label(5, 0, "Loại Tài Khoản", titleformat));
			sheet.addCell(new Label(6, 0, "Đối tác", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, list.get(i).getSoTaiKhoan(), contentformat));
				sheet.addCell(new Label(1, i + 1, list.get(i).getTenNganHang(), contentformat));
				sheet.addCell(new Label(2, i + 1, list.get(i).getChiNhanh(), contentformat));
				sheet.addCell(new Label(3, i + 1, list.get(i).getDiaChiNoiMo(), contentformat));
				sheet.addCell(new Label(4, i + 1, list.get(i).getGhiChu(), contentformat));
				sheet.addCell(new Label(5, i + 1, list.get(i).getLoaiTaiKhoanNganHang().name(), contentformat));
				sheet.addCell(new Label(6, i + 1, list.get(i).getDoiTac(), contentformat));

			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv",
					"TAI_KHOAN_NGAN_HANG.xls", "UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

	public void handleFileUpload(FileUploadEvent event) {

		logger.debug("process upload file ");
		Workbook w;
		boolean rollback = false;
		List<TaiKhoanNganHang> list = new ArrayList<TaiKhoanNganHang>();
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines

			for (int row = 1; row < sheet.getRows(); row++) {

				logger.debug("row " + row);
				Cell cell_SoTaiKhoan = sheet.getCell(0, row);
				Cell cell_NganHang = sheet.getCell(1, row);
				Cell cell_ChiNhanh = sheet.getCell(2, row);
				Cell cell_DiaChiNoiMo = sheet.getCell(3, row);
				Cell cell_GhiChu = sheet.getCell(4, row);
				Cell cell_LoaiTaiKhoanNganHang = sheet.getCell(5, row);
				Cell cell_DoiTac = sheet.getCell(6, row);

				TaiKhoanNganHang tknh = new TaiKhoanNganHang();
				tknh.setSoTaiKhoan(cell_SoTaiKhoan.getContents());
				tknh.setTenNganHang(cell_NganHang.getContents());
				tknh.setChiNhanh(cell_ChiNhanh.getContents());
				tknh.setDiaChiNoiMo(cell_DiaChiNoiMo.getContents());
				tknh.setGhiChu(cell_GhiChu.getContents());
				tknh.setLoaiTaiKhoanNganHang(LoaiTaiKhoanNganHang.valueOf(cell_LoaiTaiKhoanNganHang.getContents()));
				tknh.setDoiTac(cell_DoiTac.getContents());
				list.add(tknh);
			}
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		if (!rollback) {
			getTknganhangController().batchSaveOrUpdate(list);
		}

		loadtknganhang();
	}

	public void resetFormAdd() {
		tknganhang = new TaiKhoanNganHang();
	}

	public void notifyAdd() {
		isEdit = false;
		taiKhoaiDoiTac = true;
		resetFormAdd();
	}

	public void notifyEdit(TaiKhoanNganHang tknganhang) {
		isEdit = true;
		this.selectedtknganhang = tknganhang;
		this.tknganhang.filltknganhang(tknganhang);

		if (this.selectedtknganhang.getLoaiTaiKhoanNganHang().equals(LoaiTaiKhoanNganHang.DOI_TAC)) {
			taiKhoaiDoiTac = true;
		} else {
			taiKhoaiDoiTac = false;
		}

	}

	public void removetknganhang() {

		if (this.selectedtknganhang != null) {
			getTknganhangController().makeTransient(this.selectedtknganhang);
			loadtknganhang();
		}

	}

	public void save() {

		RequestContext context = RequestContext.getCurrentInstance();
		try {
			if (isEdit) {
				logger.debug("Edit new Tai Khoan ngan hang");

				if (this.selectedtknganhang != null) {

					getTknganhangController().makeTransient(this.selectedtknganhang);

					this.selectedtknganhang.filltknganhang(this.tknganhang);
					this.selectedtknganhang.setUpdateBy(userBean.getUser().getUserId());

					if (!taiKhoaiDoiTac)
						this.selectedtknganhang.setDoiTac(null);

					getTknganhangController().makePersistent(this.selectedtknganhang);
					// change state of parent
					context.addCallbackParam("opSuccess", true);
				}

			} else {

				logger.debug("Add new Tai Khoan ngan hang :" + this.tknganhang.getSoTaiKhoan());
				TaiKhoanNganHang tknganhang = new TaiKhoanNganHang();
				tknganhang.setCreateBy(userBean.getUser().getUserId());
				tknganhang.setUpdateBy(userBean.getUser().getUserId());

				tknganhang.filltknganhang(this.tknganhang);
				if (!taiKhoaiDoiTac)
					tknganhang.setDoiTac(null);

				getTknganhangController().makePersistent(tknganhang);

				context.addCallbackParam("opSuccess", true);

			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			logger.debug("Database error" + e.getMessage());
			context.addCallbackParam("opSuccess", false);

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		loadtknganhang();

	}

	public void loaiTaiKhoanChange(ValueChangeEvent event) {
		LoaiTaiKhoanNganHang value = (LoaiTaiKhoanNganHang) event.getNewValue();
		if (LoaiTaiKhoanNganHang.DOI_TAC.equals(value)) {

			taiKhoaiDoiTac = true;
		} else {
			taiKhoaiDoiTac = false;
		}

	}

	public void loadtknganhang() {
		if (tknganhangModel == null)
			tknganhangModel = new TaiKhoanNganHangModel();

		tknganhangModel.init();
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public void reloadPage() {
		loadtknganhang();
		WebUtil.redirect("/pages/danhmuc/TaiKhoanNganHang.xhtml");
	}

	public TaiKhoanNganHangModel getTknganhangModel() {
		return tknganhangModel;
	}

	public void setTknganhangModel(TaiKhoanNganHangModel tknganhangModel) {
		this.tknganhangModel = tknganhangModel;
	}

	public TaiKhoanNganHang getTknganhang() {
		return tknganhang;
	}

	public void setTknganhang(TaiKhoanNganHang tknganhang) {
		this.tknganhang = tknganhang;
	}

	public TaiKhoanNganHang getSelectedtknganhang() {
		return selectedtknganhang;
	}

	public void setSelectedtknganhang(TaiKhoanNganHang selectedtknganhang) {
		this.selectedtknganhang = selectedtknganhang;
	}

	public LoaiTaiKhoanNganHang[] getListLoaiTKNganHang() {
		return LoaiTaiKhoanNganHang.values();
	}

	public boolean isTaiKhoaiDoiTac() {
		return taiKhoaiDoiTac;
	}

	public void setTaiKhoaiDoiTac(boolean taiKhoaiDoiTac) {
		this.taiKhoaiDoiTac = taiKhoaiDoiTac;
	}

}
